/**
 * author: Hanflyee  flyee1980@163.com
 * vision: v1.0
 * data: 2009-7-9
 */
package com.flyee.service{
	
	import com.flyee.controller.CharacterCartoonController;
	import com.flyee.controller.CharactorMoveController;
	import com.flyee.controller.SceneController;
	import com.flyee.controller.UIController;
	import com.flyee.controller.timer.CartoonTimer;
	import com.flyee.controller.timer.WalkTimer;
	import com.flyee.controller.tools.path.AStar;
	import com.flyee.io.socket.CommandUpSender;
	import com.flyee.model.Charactor;
	import com.flyee.ro.commandup.JoinRoomUp;
	import com.flyee.ro.commandup.LoginUp;
	import com.flyee.ro.commandup.LogoutUp;
	import com.flyee.ro.commandup.QuitRoomUp;
	import com.flyee.ro.commandup.RoadPathUp;
	import com.flyee.ro.rpc.AvatarRO;
	import com.flyee.service.pool.ObjectCollection;
	import com.flyee.utils.CoodinateUtil;
	import com.flyee.utils.MyLog;
	import com.flyee.utils.Obsevable;
	import com.flyee.utils.Obsever;
	import com.flyee.viewer.CharactorViewer;
	
	import flash.events.MouseEvent;
	import flash.geom.Point;	
	
	/**
	 * C层，人物相关管理类
	 */
	public class CharactorService implements Obsever{
		[Inject]
		public var commandSender : CommandUpSender;
		[Inject]
		public var moveController : CharactorMoveController;
		[Inject]
		public var cartoonController : CharacterCartoonController;
		[Inject]
		public var sceneController : SceneController;
		[Inject]
		public var uiController : UIController;
				
		public function CharactorService(){
		}

		/**
	     * 接到被观察者通知后执行
	     * @param o 被观察者
	     * @param command 指令
	     * @param args 参数
	     */
	    public function execute(o : Obsevable, command : String = null, args : * = null) : void {
	        switch (command) {
	            case "choiceAvatar" :
	                choiceAvatar();
	                break;
	            case "initAvatars" :
	                initAvatars(args[0]);
	                break;
	            case "addAvatar" :
	                addAvatar(args[0]);
	                break;
	            case "move" :
	                move(args[0],args[1],args[2],args[3]);
	                break;
	            case "synchronize" :
//	            	synchronize(args[0], args[1], args[2],args[3]);
	            	break;
	            case "quitRoom" :
	                quitRoom(args[0]);
	                break;
	            default :
	                //MyLog.debug("command is null!");
	                break;
	        }
	    }
		
		/**登入系统*/
		public function login(c : Charactor) : void {
			var loginUp : LoginUp = new LoginUp();
			loginUp.handler = "loginHandler";
			loginUp.sceneId = c.sceneId;
			loginUp.sceneInstanceId = c.sceneInstanceId;
			loginUp.sender = c.gcode;
			commandSender.send(loginUp);
			MyLog.debug("login waiting");
		}
		
		/**退出*/
		public function logout() : void {
			var logoutUp : LogoutUp = new LogoutUp();
			logoutUp.sender = ObjectCollection.master.id;
			logoutUp.sceneId = ObjectCollection.master.sceneId;
			logoutUp.sceneInstanceId = ObjectCollection.master.sceneInstanceId;
			commandSender.send(logoutUp);
			MyLog.debug("logout!");
		}
		
		/**退出场景*/
		public function quitRoom(id : String) : void {
			var char : Charactor = ObjectCollection.getCharacter(id);
			if(char == null) return;
			var charUI : CharactorViewer = ObjectCollection.getCharacterViewerByMid(char.mid);
			ObjectCollection.charactorMap.remove(char.mid);
			ObjectCollection.currentSceneViewer.componentLayer.removeChild(charUI);
			ObjectCollection.charactorViewerMap.remove(charUI.vid);
			ObjectCollection.removeRelationByMid(char.mid);
			var cartoonTimer : CartoonTimer = ObjectCollection.cartoonTimerMap.remove(charUI.vid) as CartoonTimer;
			cartoonTimer.dispose();
			var moveTimer : WalkTimer = ObjectCollection.moveTimerMap.remove(charUI.vid) as WalkTimer;
			if(moveTimer != null)
				moveTimer.dispose();
			if(ObjectCollection.master.target == char){
//				ObjectCollection.targetWindowViewer.visible = false;
				ObjectCollection.master.target = null;
			}
			charUI.dispose();
		}
		
		/**登陆成功,选择已创建的角色（由于功能未做，直接执行进入场景）*/
		public function choiceAvatar() : void {
			var joinRoomUp : JoinRoomUp = new JoinRoomUp();
			joinRoomUp.handler = "joinRoomHandler";
			joinRoomUp.sceneId = ObjectCollection.master.sceneId;
			joinRoomUp.sceneInstanceId = ObjectCollection.master.sceneInstanceId;
			joinRoomUp.sender = ObjectCollection.master.gcode;
			commandSender.send(joinRoomUp);
			MyLog.debug("Join room waiting");
		}
		
		/**进入场景*/
		public function enterInScene() : void {
			var charUI : CharactorViewer;
			if(ObjectCollection.masterViewer != null)
				charUI = ObjectCollection.masterViewer;
			else
				charUI = cartoonController.initCharacterViewer(ObjectCollection.master);
			ObjectCollection.master.x = ObjectCollection.currentScene.charx;
			ObjectCollection.master.y = ObjectCollection.currentScene.chary;
			moveController.addCharactor(ObjectCollection.master, charUI, ObjectCollection.currentSceneViewer.componentLayer);
		}
		
		/**初始化场景中玩家*/
		public function initAvatars(avatars : Array) : void {
			enterInScene();
			addAvatars(avatars);
		}
		
		/**加载新进入场景玩家*/
		public function addAvatars(playerArr : Array) : void {
			//取得进入的玩家数组
			for each(var avatar : AvatarRO in playerArr){
				addAvatar(avatar);
			}
		}
		
		public function addAvatar(avatar : AvatarRO) : void {
			var player : Charactor = new Charactor();
			player.id = avatar.avatarId;
			player.gcode = avatar.avatarId;
			if(avatar.hp<0)
				avatar.hp = 0;
			player.hp = avatar.hp;
			player.mySex = 0;
			player.name = "游客" + avatar.avatarId;
			player.sceneId = ObjectCollection.DEFAULT_SCENE_ID;
			player.x = avatar.startX;
			player.y = avatar.startY - ObjectCollection.currentScene.offsetY;	
			MyLog.debug(player.id + " enter scene.");
			ObjectCollection.charactorMap.put(player.mid, player);
			var charUI : CharactorViewer = cartoonController.initCharacterViewer(player);			
			moveController.addCharactor(player, charUI, ObjectCollection.currentSceneViewer.componentLayer);
//			if(player.hp == 0){
//				cartoonController.playerDie(charUI);
//			}
		}
		
		/**切换场景*/
		public function switchScene(sceneID : String, charX : Number, charY : Number) : void {
			moveController.depthTimer.stop();
			//销毁现场景
			for each(var char : Charactor in ObjectCollection.charactorMap.values()){
				this.quitRoom(char.id);
			}
			sceneController.unloadScene();
			//发出退出现场景指令
			var quitRoomCmd : QuitRoomUp = new QuitRoomUp();
			quitRoomCmd.sender = ObjectCollection.master.gcode;
			quitRoomCmd.sceneId = ObjectCollection.master.sceneId;
			quitRoomCmd.sceneInstanceId = ObjectCollection.master.sceneInstanceId;
			commandSender.send(quitRoomCmd);
			//发出进入新场景指令
			ObjectCollection.master.x = 0;
			ObjectCollection.master.y = 0;
			ObjectCollection.master.sceneId = sceneID;
			ObjectCollection.master.sceneInstanceId = sceneID;
			var joinRoomUp : JoinRoomUp = new JoinRoomUp();
			joinRoomUp.handler = "joinRoomHandler";
			joinRoomUp.sceneId = sceneID;
			joinRoomUp.sceneInstanceId = sceneID;
			joinRoomUp.sender = ObjectCollection.master.gcode;
			commandSender.send(joinRoomUp);
		}

		/**客户端寻路*/
		public function requestPath(event : MouseEvent) : void {
			if(ObjectCollection.master.hp == 0) return ;
//			if(ObjectCollection.master.skillStatus) return ;
			if(ObjectCollection.master.waitMoveStatus) return ;
			this.moveController.pausePlayerMove(ObjectCollection.masterViewer);
			var start : Point = new Point(ObjectCollection.master.x, ObjectCollection.master.y + ObjectCollection.currentScene.offsetY);
			//转换坐标系
			var end : Point = CoodinateUtil.convertToObliqueXY(new Point(
													ObjectCollection.currentSceneViewer.mouseX - 40, 
													ObjectCollection.currentSceneViewer.mouseY)); 
			end.y += ObjectCollection.currentScene.offsetY;
//			var aStar : AStar = new AStar(ObjectCollection.mapData);
			var pathArr : Array = AStar.findPath(start.y, start.x, end.y, end.x);
			if(pathArr == null) return ;
			//发出请求
			var cmd : RoadPathUp = new RoadPathUp();
			cmd.startX = start.x;
			cmd.startY = start.y;
			cmd.targetX = end.x;
			cmd.targetY = end.y;
			cmd.panes = pathArr;
			cmd.sceneId = ObjectCollection.master.sceneId;
			cmd.sceneInstanceId = ObjectCollection.master.sceneInstanceId;
			cmd.sender = ObjectCollection.master.id;
			commandSender.send(cmd);
			move(ObjectCollection.master.gcode, start.x, start.y, pathArr, true);
		}
		
		/**人物行走*/
		public function move(playerId : String, startX : int, startY : int, pathArr : Array, b : Boolean = false) : void {
			if(playerId == ObjectCollection.master.gcode)
				if(!b)
					return ;
			var player : Charactor = ObjectCollection.getCharacter(playerId);
			if(player == null) return ;
			if(player.hp == 0) return ;
			var playerV : CharactorViewer = ObjectCollection.getCharacterViewerByMid(player.mid);
			if(moveController.checkSynchronize(player, startX, startY-ObjectCollection.currentScene.offsetY)){
				moveController.move(player, playerV, pathArr);
			}else{
				moveController.synchronizeHandler(player, playerV, startX, startY-ObjectCollection.currentScene.offsetY, pathArr);
			}
		}
		
		/**位置同步*/
		public function synchronize(playerId : String, x : Number, y : Number, pathArr : Array) : void {
			var player : Charactor = ObjectCollection.getCharacter(playerId);
			if(player == null) return ;
			var playerV : CharactorViewer = ObjectCollection.getCharacterViewerByMid(player.mid);
			if(moveController.checkSynchronize(player, x, y-ObjectCollection.currentScene.offsetY)){
				moveController.move(player, playerV, pathArr);
			}else{
				moveController.synchronizeHandler(player, playerV, x, y-ObjectCollection.currentScene.offsetY, pathArr);
			}
		}
		
		/**设置人物可见*/
		public function setPlayerVisible(value : Boolean) : void {
			cartoonController.setPlayersVisible(value);
		}

	}
	
}